/**
 * 
 */

	
$(document).ready(function() {
	
	//tab	
	$('.osbspztab > li').on('click',function(){
		$(this).addClass('current').siblings().removeClass('current');
		var tab = $(this).attr('title');
		$('#' + tab).show().siblings().hide();
	});
	
	//绑定bootstrap输入提示
	 $("#iso_name").typeahead({
		  source: osList,  // 绑定数据源
		  highlighter: function (item) {
		      return item.split("-\$-")[0];
		  },
		  updater: function (item) {
		      return item.split("-\$-")[0];
		  },
		  afterSelect: function (item) {
		  }
	  });
	 
	 
	 $("#copy_iso_name").typeahead({
		  source: osList,  // 绑定数据源
		  highlighter: function (item) {
		      return item.split("-\$-")[0];
		  },
		  updater: function (item) {
		      return item.split("-\$-")[0];
		  },
		  afterSelect: function (item) {
		  }
	  });
	 
	 $('#raid_inp').typeahead({
		  source: ['/','/boot','/home','/var','/tmp','/usr','/opt']  // 绑定数据源
	 });
	 
	 
	//给form 表单绑定jquer验证组件
	$( "#signupForm1" ).validate( {
		rules: {
			conf_name:  {
				required: true,
				checkConfig:true
			},
			iso_name:{
				required: true,
				checkOsName: osList
			},
			root_pwd_confirm:{
				check_root_pwd: true
			},
			note_inp:{
				required: true
			}
		},
		messages: {
			conf_name: {
				required:getConfiError1(),
				checkConfig:getConfiError2()
			},
			iso_name:{
				required: getConfiError3(),
				checkOsName: getConfiError4()
			},
			note_inp:{
				required: getConfiError6()
			},
			root_pwd_confirm:getConfiError5()
		},
		errorElement: "p",
		errorPlacement: function ( error, element ) {
			error.addClass('error_tip');
			var firstPar = $(element).parent();
			if(firstPar.is('li')){
				firstPar.addClass('error');
				error.insertAfter($(element));
				error[0].style.left = "80px";
			}else{
				firstPar.parent().addClass('error');
				error.insertAfter($(element).parent('.infoli'));
			}
		},
		success: function ( label, element ) {
			var firstPar = $(element).parent()[0];
			if(firstPar.tagName == 'li'){
				$(firstPar).removeClass('error');
				$(element).next('p').remove();
			}else{
				$(firstPar).parent().removeClass('error');
				$(element).parent('.infoli').next('p').remove();
			}
		},
		highlight: function ( element, errorClass, validClass ) {
			$( element ).parents( ".col-sm-5" ).addClass( "has-error" ).removeClass( "has-success" );
			$( element ).next( "span" ).addClass( "glyphicon-remove" ).removeClass( "glyphicon-ok" );
		},
		unhighlight: function ( element, errorClass, validClass ) {
			$( element ).parents( ".col-sm-5" ).addClass( "has-success" ).removeClass( "has-error" );
			$( element ).next( "span" ).addClass( "glyphicon-ok" ).removeClass( "glyphicon-remove" );
		}
	} );

	//初始化待选安装软件列表
	$('#packages_sou div h4').on('click',function(){
		var curCls = $(this).parent().attr('class');
		if(curCls == 'perinfo_close'){
			$(this).parent().removeClass().addClass("perinfo_open");
			$(this).parent().siblings().removeClass().addClass("perinfo_close");
		}else{
			$(this).parent().removeClass().addClass("perinfo_close");
		}
	});
	
	$('#packages_sou div ul li').on('click',function(){
		var curCls = $(this).attr('class');
		if(curCls !='current'){
			var li = $(this).clone();
			li.appendTo($('#packages_tar ul'));
			li.on('click',function(){
				var tittle = $(this).attr("title");
				$('#packages_sou div ul li').each(function(i,data){
					var tempTitle = $(data).attr('title');
					if(tittle == tempTitle){
						$(data).removeClass();
						return false;
					}
				});
				$(this).remove();
			});
			$(this).addClass('current');
		}
	});
	
	$('#packages_tar ul li').on('click',function(){
		var tittle = $(this).attr("title");
		$('#packages_sou div ul li').each(function(i,data){
			var tempTitle = $(data).attr('title');
			if(tittle == tempTitle){
				$(data).removeClass();
				return false;
			}
		});
		$(this).remove();
	});
	
	//初始化待选安装后脚本
	$('#shl_sou div h4').on('click',function(){
		var curCls = $(this).parent().attr('class');
		if(curCls == 'perinfo_close'){
			$(this).parent().removeClass().addClass("perinfo_open");
			$(this).parent().siblings().removeClass().addClass("perinfo_close");
		}else{
			$(this).parent().removeClass().addClass("perinfo_close");
		}
	});
	
	$('#shl_sou div ul li').on('click',function(){
		var curCls = $(this).attr('class');
		if(curCls !='current'){
			var li = $(this).clone();
			li.appendTo($('#shl_tar ul'));
			li.on('click',function(){
				var tittle = $(this).attr("title");
				$('#shl_sou div ul li').each(function(i,data){
					var tempTitle = $(data).attr('title');
					if(tittle == tempTitle){
						$(data).removeClass();
						return false;
					}
				});
				$(this).remove();
			});
			$(this).addClass('current');
		}
	});
	
	$('#shl_tar ul li').on('click',function(){
		var tittle = $(this).attr("title");
		$('#shl_sou div ul li').each(function(i,data){
			var tempTitle = $(data).attr('title');
			if(tittle == tempTitle){
				$(data).removeClass();
				return false;
			}
		});
		$(this).remove();
	});
	
	var page = refreshKsData('',1);
	createTable(page.ksList);
	initPage(page);
	
});

function quicSsearchCallback(){
	var  ipdata =refreshKsData($('#ks_search').val().replace(/(^\s*)|(\s*$)/g, ""),1);
	createTable(ipdata.ksList);
	initPage(ipdata);
};
/**
 * 初始化页面
 */
var initPage =function(page){
	var totalCount = Number(page.totalCount)|| 1;
	var showPage = 10;
	var showCount = 20;
	var currentPage = Number(page.currentPage) || 1;
	$('#callBackPager').empty();
	$('#callBackPager').extendPagination({
		totalCount : totalCount,
		showPage : showPage,
		showCount : showCount,
		currentPage : currentPage,
		callback : function(curr, showCount, totalCount) {
			var page = refreshKsData($('#ks_search').val().replace(/(^\s*)|(\s*$)/g, ""),curr);
			createTable(page.ksList);
		}
	});
};
/**
 * 刷新Ip列表
 * @param ks_search 搜索
 * @param currentPage 当前页面
 * 
 */
var refreshKsData = function(ks_search,currentPage){
	//初始化页面table数据
	var data1 = {};
	var ks_search = $('#ks_search').val();
	data1.ks_search =ks_search;
	data1.currentPage = currentPage;
	var returnData = ajaxWithServer(null, data1, 'getKsData');
	var dataList = returnData.ksList;
	if (undefined == dataList) {
		dataList = [];
	}
	return returnData;
};
/**
 * 是否自动生成密码
 */
var rodom_check = function(data){
	
	var checked = $(data).is(':checked');;
	if(checked){
		var firstPar = $('#root_pwd_confirm').parent()[0];
		if(firstPar.tagName == 'li'){
			$(firstPar).removeClass('error');
			$(element).next('p').remove();
		}else{
			$(firstPar).parent().removeClass('error');
			$('#root_pwd_confirm').parent('.infoli').next('p').remove();
		}
		var pwd = password(6,false);
		$('#root_pwd').attr("disabled",true).val(pwd);
		$('#root_pwd_confirm').attr("disabled",true).val(pwd);
	}else{
		$('#root_pwd').attr("disabled",false).val("");
		$('#root_pwd_confirm').attr("disabled",false).val("");
	}
};
/**
 * 新增或修改的操作
 * 
 * @param option
 *            新增或修改
 * 
 */
var addOrUpdate = function(option) {
	if (option == "add") {
		$('#ksOption').val("add");
		$('#note_div').hide();
	} else {
		$('#ksOption').val("update");
		$('#note_div').show();
		var allCheck = getSeletcRows()[0];
		$('#tr_os_table').val($(allCheck).index());
		var id = $(allCheck).find('td input[type="checkbox"]').attr('id');
		var data = {"id":id};
		var returnData = ajaxWithServer(null,data,'getKsFile');
		//alert(returnData);
		$('#csaId').val(id);
		fillKisckstart(returnData);
	}
	$('#main_content').css('display', 'none');
	$('#ks_content').css('display', 'block');
};




/**
 * Data interaction with the background server
 * 
 * @param opType
 *            optioion type
 * @param data
 *            send to background server with json type
 * @param action
 *            request mapping
 */
var ajaxWithServer = function(opType, data, action) {
	var json = {};
	$.ajax({
		type : "POST",
		datatype : "json",
		contentType : "application/json; charset=utf-8",
		url : action,
		async : false,
		data : JSON.stringify(data),
		success : function(dataJson) {
			json = dataJson;
		},
		error : function() {
			json.result = false;
			json.message = "Net error!";
		}
	});
	return json;
};


/**
 * 向后台保存ks信息
 * @return 保存结果信息
 */
var saveToServer = function (){
	var opType = $('#ksOption').val();
	
	var ksData = {};
	//基本信息
	ksData.opType=opType;
	ksData.conf_name =  $('#conf_name').val().replace(/(^\s*)|(\s*$)/g, "");
	ksData.iso_name = $('#iso_name').val().replace(/(^\s*)|(\s*$)/g, "");
	ksData.lan_in = $('#lan_in').val();
	ksData.time_zone = $('#time_zone').val();
	ksData.root_pwd = $('#root_pwd').val().replace(/(^\s*)|(\s*$)/g, "");
	ksData.radom_pwd = $('#radom_pwd').is(':checked');
	ksData.reboot_ch = $('#reboot_ch').is(':checked');
	ksData.csaId = $('#csaId').val().replace(/(^\s*)|(\s*$)/g, "");
	var discPart = [];
	//分区信息
	$('#disc_tb tr').each(function (){
		if($(this).index() == 0)
			return true;
		discPart.push({'raid':$(this).find('td:first').text(),'type':$(this).find('td').eq(1).text(),'size':$(this).find('td').eq(2).text()});
	});
	ksData.discPart = discPart;
	
	var insSoft = [];
	$('#packages_tar ul li').each(function(){
		insSoft.push($(this).attr('title'));
	});
	ksData.insSoft= insSoft;
	
	var shellFile  = [];
	$('#shl_tar ul li').each(function(){
//		var temp = {'csaId':$(this).attr('title'),'fileName':$(this).find('a').text()};
		shellFile.push($(this).attr('title'));
	});

	ksData.shellFile = shellFile;
	ksData.note = $('#note_inp').val().replace(/(^\s*)|(\s*$)/g, "");
	
	return ajaxWithServer(null,ksData,'editKickstart');
};
/**
 * 挂载点类型改变
 */
var chDisType = function(data){
	var val = $(data).val();
	if(val == 'swap'){
		//使挂载点不可操作
		$('#raid_inp').val('swap').attr("disabled",true);
	}else{
		$('#raid_inp').val('').attr("disabled",false);
	}
};
/*
 * 构建待选软件包
 * @param data 待选软件包集合
 */
var builderPackagesList = function (data){
	var ul = $('#packageCol');
	ul.empty();
	$.each(data,function(p1,p2){
		//<li><input type="checkbox"  value=""> DNS 名称服务器</li>
		$('<li><input type="checkbox" id="'+this.csaId+'"  value="'+this.csaId+'"><label for="'+this.csaId+'">'+this.packageName+'</label></li>').appendTo(ul);
	});
};

/**
 * 编辑系统分区
 * @param option 操作类型
 * 
 */
var editSystemArea = function(data){
	var raid_inp = "";
	var size_inp = "";
	var sys_inp = "";
	if (data == "add") {
		$("#optionType").val("add");
		sys_inp = "ext4";
	} else {
		// update
		$("#optionType").val("update");
		$('#trIndex').val($(data).parent().parent().index());
		raid_inp = $(data).parent().parent().find('td:first').text();
		sys_inp = $(data).parent().parent().find('td').eq(1).text();
		size_inp = $(data).parent().parent().find('td').eq(2).text();
	}
	if(raid_inp == 'swap'){
		$('#raid_inp').attr("disabled",true);
	}else{
		$('#raid_inp').attr("disabled",false);
	}
	$('#raid_inp').val(raid_inp);
	$('#size_inp').val(size_inp);
	$("#sys_inp option").each(function(){
		if( $(this).text() == sys_inp){
			$(this).attr("selected", "selected");
			return false;
		}
	});
	$('#os3_ipfp').show("slow");
};

var closePop = function(data) {
	$('#os3_ipfp').hide("slow");
	$('#errorLi').remove();
};


var closePop2 = function(){
	$('#os_copy').hide("slow");
	$('#cp_os_ul li[class="pop_error"]').remove();
	clearFill();
};
var clearFill = function(){
	$('#copy_conf_name').val('');
	$('#copy_iso_name').val('');
};
/**
 * 批量删除kickstart文件
 * 
 */
var deleteKickstarts = function (){
	// get the count of the checkbox
	table = $("#os_table");
	trs = table.find("tr");
	var count = 0;
	var ids = [];
	trs.each(function() {
		try {
			var checkBox = $(this).find("td input[type='checkbox']");
			if (checkBox.is(':checked')) {
				count++;
				ids.push(checkBox.attr('id'));
			}
		} catch (e) {
			// ignore th for table
		}
	});
	
	swal({
		title : getSpringMsg('Delete',null),
		text : getSpringMsg('ConfirmDeleteIps',count),
		type: "warning",
		showCancelButton: true,   
		confirmButtonColor: "#DD6B55",   
		confirmButtonText: getSpringMsg("okdelete",null),   
		cancelButtonText: getSpringMsg("cancel",null),   
		closeOnConfirm: false,   
		closeOnCancel: true
	},
	function(isConfirm) {
		if(isConfirm){
			var data = {};
			data.ids = ids.join(",");

			var resultJs = ajaxWithServer(null, data, "deleteKickstarts");
			if (resultJs.result)
				window.location.href = "osdeploy";
			else
				swal("Message!",resultJs.message);
		}
	});
};

var removeSystemDis = function(data){
	$(data).parent().parent().remove();
};
/**
 * 检测是否是有效的字符
 * @param value 要验证的值
 * @param tb_id  id for talbe
 * @param colum 第几列
 * @param opType 操作类型
 */
var validateStr = function(value, tb_id,colum,opType){
	var trs = $("#" + tb_id + " tr");
	var trIndex = $('#trIndex').val();
	var isExist = false;
	trs.each(function() {
		try {
			if (opType == "update") {
				if ($(this).index() == trIndex)
					return true;
			}
			var temp = $(this).find("td").eq(colum - 1).text();
			if (temp == value) {
				isExist = true;
				return false;
			}
		} catch (e) {
			// TODO: handle exception
		}
	});
	return isExist;
};
/**
 * 验证配置名称是否有重复
 */
var validateConfig = function(value, tb_id){
	var trs = $("#" + tb_id + " tr");
	var isExist = false;
	trs.each(function() {
		try {
			var temp = $(this).find("td input[type='checkbox']").val();
			if (temp == value) {
				isExist = true;
				return false;
			}
		} catch (e) {
			// TODO: handle exception
		}
	});
	return isExist;
};
/**
 * 检查景象名称是否符合规则
 */
var validateIOS = function(value,param){
	var isFormat = false;
	$.each(param,function(){
		var temp = this.split('-\$-')[0].replace(/(^\s*)|(\s*$)/g, "");
		if(value== temp){
			isFormat = true;
			return false;
		}
	});
	return isFormat;
};

/**
 * 获取当前table选中的所有的行
 * 
 * @author GuoPengFei
 * @date 2016-04-14
 */
var getSeletcRows = function() {
	var trs = $("#os_div table tr");
	// trs = table.children("tr");
	var allChecked = [];
	trs.each(function() {
		try {
			tempChecked = $(this).find("td input[type='checkbox']").is(
					':checked');
		} catch (e) {
			return true;
		}
		// 计数被选择的个数
		if (tempChecked)
			allChecked.push(this);
	});

	return allChecked;
};
/**
 * 拷贝kickstart文件
 * 
 */
var copyKickstart = function(){
	var allSelect = getSeletcRows()[0];
	$('#trIndex').val($(allSelect).index());
	$('#csaId').val($(allSelect).find('td input[type="checkbox"]').attr('id'));
	
	$('#os_copy').show("slow");
	
};